package com.ruoyi.fire.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.ResponseEntityInfo;
import com.ruoyi.common.enums.RequestMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RequestService;
import com.ruoyi.fire.domain.EMaintenanceUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.fire.mapper.ERegionMapper;
import com.ruoyi.fire.domain.ERegion;
import com.ruoyi.fire.service.IERegionService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 行政区域Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ERegionServiceImpl extends ServiceImpl<ERegionMapper, ERegion> implements IERegionService {
    @Autowired
    private ERegionMapper eRegionMapper;

    private final RequestService requestService;

    /**
     * 查询行政区域
     *
     * @param id 行政区域主键
     * @return 行政区域
     */
    @Override
    public ERegion selectERegionById(Long id) {
        return eRegionMapper.selectERegionById(id);
    }

    /**
     * 查询行政区域列表
     *
     * @param eRegion 行政区域
     * @return 行政区域
     */
    @Override
    public List<ERegion> selectERegionList(ERegion eRegion) {
        return eRegionMapper.selectERegionList(eRegion);
    }

    /**
     * 新增行政区域
     *
     * @param eRegion 行政区域
     * @return 结果
     */
    @Override
    public int insertERegion(ERegion eRegion) {
        return eRegionMapper.insertERegion(eRegion);
    }

    /**
     * 修改行政区域
     *
     * @param eRegion 行政区域
     * @return 结果
     */
    @Override
    public int updateERegion(ERegion eRegion) {
        eRegion.setUpdateTime(DateUtils.getNowDate());
        return eRegionMapper.updateERegion(eRegion);
    }

    /**
     * 批量删除行政区域
     *
     * @param ids 需要删除的行政区域主键
     * @return 结果
     */
    @Override
    public int deleteERegionByIds(Long[] ids) {
        return eRegionMapper.deleteERegionByIds(ids);
    }

    /**
     * 删除行政区域信息
     *
     * @param id 行政区域主键
     * @return 结果
     */
    @Override
    public int deleteERegionById(Long id) {
        return eRegionMapper.deleteERegionById(id);
    }

    /**
     * 数据同步
     *
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dataSync() {
        try {
            ResponseEntityInfo responseEntityInfo = requestService.advancedRequest(RequestMapper.PROVINCE_LIST, null);
            if (responseEntityInfo != null && responseEntityInfo.getErrno() == 0) {
                Object data = responseEntityInfo.getData();
                if (data == null) {
                    // 记录警告日志：返回数据为空
                    return;
                }

                // 使用条件删除替代全表删除，绕过保护机制
                getBaseMapper().delete(new LambdaQueryWrapper<ERegion>().isNotNull(ERegion::getId));
                List<ERegion> eRegions = JSON.parseArray(JSON.toJSONString(data), ERegion.class);
                if (eRegions != null && !eRegions.isEmpty()) {
                    // 设置更新时间
                    eRegions.forEach(item -> item.setUpdateTime(DateUtils.getNowDate()));
                    saveBatch(eRegions);

                    // 同步子级数据（最多两层）
                    syncSubRegions(eRegions, 2);
                }
            }
        } catch (Exception e) {
            // 记录错误日志
            throw new RuntimeException("数据同步过程中发生异常", e);
        }
    }

    /**
     * 递归同步子级区域数据
     *
     * @param parentRegions 父级区域列表
     * @param maxDepth      最大深度限制
     */
    private void syncSubRegions(List<ERegion> parentRegions, int maxDepth) {
        if (maxDepth <= 0 || CollectionUtils.isEmpty(parentRegions)) {
            return;
        }

        for (ERegion parent : parentRegions) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("region_id", parent.getId());

                ResponseEntityInfo responseEntityInfo = requestService.advancedRequest(RequestMapper.CHILDREN_LIST, params);
                if (responseEntityInfo == null || responseEntityInfo.getErrno() != 0) {
                    log.warn("获取子地区列表失败，父ID={}", parent.getId());
                    continue;
                }

                Object data = responseEntityInfo.getData();
                if (data == null) {
                    log.warn("子地区列表数据为空，父ID={}", parent.getId());
                    continue;
                }

                List<ERegion> subRegions = JSON.parseArray(JSON.toJSONString(data), ERegion.class);
                if (!CollectionUtils.isEmpty(subRegions)) {
                    subRegions.forEach(region -> region.setUpdateTime(DateUtils.getNowDate()));
                    saveBatch(subRegions);

                    // 递归同步下一级
                    syncSubRegions(subRegions, maxDepth - 1);
                }
            } catch (Exception e) {
                log.error("同步子级区域数据异常，父ID={}", parent.getId(), e);
                throw new RuntimeException("同步子级区域数据过程中发生异常", e);
            }
        }
    }
}
